$(function() {
	var txtKeywordsMaxNum, productTitle, txtKeywordsToSearch;
	var keywordMarket = "美国亚马逊";
	var keySpanL = 0;
	var randSum = 0;
	var span;
	var spanArry = [];
	var spanArrys = [];
	var Spider_Job_ID = ""; //随机ID
	/*获取Amazon平台的值*/
	var radioBtn = $(".radioContainer").find(".keyRadioMsg");
	radioBtn.on("click", function() {
		var Market = $(this).children(".rMsg").text();
		keywordMarket = Market;
	})

	$(".keyInput").on("keyup", function() {
		if ($(this).hasClass("txtKeywordsToSearch")) {
			span = $(this).val();
		} else {
			compare();
		}
	})

	/*核心关键词*/
	$(".keysWords input").blur(function() {
		var txtInputValueLen = trim($("#txtKeywordsToSearch").val());
		if (txtInputValueLen.length == 0) {
			return;
		}
		keySpanFor($(this));
		for (var i = 0; i < spanArrys.length; i++) {
			if (trim($("#txtKeywordsToSearch").val()) == spanArrys[i]) {
				$(this).val("");
				return;
			}
		}
		creatKeySpan($(this));
		KeywordsToSearch();
	})

	/*核心关键词回车事件 */
	$(".keysWords input").on("keydown", function(e) {
		if (e.keyCode == 13) {
			var txtInputValueLen = trim($("#txtKeywordsToSearch").val());
			if (txtInputValueLen.length == 0) {
				return;
			}
			keySpanFor($(this));
			for (var i = 0; i < spanArrys.length; i++) {
				if (trim($("#txtKeywordsToSearch").val()) == spanArrys[i]) {
					$(this).val("");
					return;
				}
			}
			creatKeySpan($(this));
			KeywordsToSearch()
		}
	})

	/*查找核心关键词是否有相同值存在 */
	function keySpanFor(obj) {
		//先判断是否生成了spanMsg，如果有就循环进行值比较，是否存在相同的值
		if (obj.siblings("div").hasClass("keySpanS")) {
			$(".keySpanS").each(function() {
				var spanValue = $(this).children(".keySpan").children("span").text();
				var dataIndex = $(this).children(".keySpan").attr("data-index");
				if (spanValue == trim($("#txtKeywordsToSearch").val())) {
					$(this).children(".keySpan").css("background", "red");
					$(".tags input").val(" ");
					setTimeout("chageSpanBk(" + dataIndex + ")", 500);
					return false;
				}
			})
		}
	}

	/*核心关键词删除事件 */
	$(".keysWords input").on("keydown", function(e) {
		if (e.keyCode == 8) {
			removekeySpans($(this));
		}
	})

	function creatKeySpan(_this) {
		_this.css("border", "0")
		var inputValue = _this.val();
		if (inputValue == " ") {
			return
		}
		var len = spanArrys.length;
		len++;
		var _html = "";
		_html += '<div class="keySpanS">';
		_html += '<span class="keySpan ks' + len + '" data-index="' + len + '">';
		_html += '<span>' + inputValue + '</span>';
		_html += '<div class="closeBtn closeClick">×</div>';
		_html += '</span></div>';
		_this.before(_html);
		_this.val("");
	}

	/*核心关键词关闭按钮*/
	$(".keysWords").on("click", "div[class~=closeClick]", function() {
		alert("1")
		$(this).parent().parent().remove();
		spanArrys = [];
		KeywordsToSearch();
		spanArry = [];
	})

	/*删除核心关键词的单词*/
	function removekeySpans(_this) {
		if (trim(_this.val()).length == 0) {
			$(".keysWords").children().siblings(".keySpanS").last().remove();
			spanArrys = [];
			KeywordsToSearch();
			spanArry = [];
		}
	}

	function KeywordsToSearch() {
		keySpanL = $(".keysWords").find(".keySpanS").length;
		var spanVlaue;
		if (keySpanL > 0) {
			$(".keySpanS").each(function() {
				var spanV = $(this).children().children("span").html();
				spanArry.push(spanV);
				spanArrys.push(spanV);
			})
			spanVlaue = spanArry[0];
			for (var i = 0; i < spanArry.length; i++) {
				if (i > 0) {
					spanVlaue += "|||" + spanArry[i];
				}
			}
			txtKeywordsToSearch = spanVlaue;
		}
		compare();
		spanArry = [];
	}

	function compare() {
		if (inputEmpty() == true && keySpanL > 0) {
			$(".keyStranClick").css({
				"cursor": "pointer",
				"opacity": "1",
				"filter": "progid:DXImageTransform.Microsoft.Alpha(opacity=100)",
				"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(opacity=100)"
			}).addClass("countBtn stratHover");
		} else {
			$(".keyStranClick").css({
				"cursor": "no-drop",
				"opacity": ".6",
				"filter": "progid:DXImageTransform.Microsoft.Alpha(opacity=60)",
				"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(opacity=60)"
			}).removeClass("countBtn stratHover");
		}
	}

	/*判断输入框不能为空*/
	function inputEmpty() {
		txtKeywordsMaxNum = ($("#txtKeywordsMaxNum").val() == "") ? "" : $("#txtKeywordsMaxNum").val();
		productTitle = ($("#productTitle").val() == "") ? "" : $("#productTitle").val();

		if (txtKeywordsMaxNum != "") {
			return true;
		} else {
			return false;
		}

	}
	/*抓一抓按钮*/
	$(".keyStranClick").on("click", function() {
		var data = "";
		if ($(this).hasClass("stratHover")) {
			if ($(this).text() == '抓一抓') {
				/*清空所有结果文本框*/
				$("input[class*=copy_txt]").val("");
				$(".updataTextArea").html("");
				$(".divDisplay").hide();
				/*点击按钮就显示10到20的进度条*/
				randSum = Math.ceil((Math.random() * 10) + 10);
				$(".progress-bar").css("width", randSum + "%");

				$(".progressMsg").text("正在抓取：" + spanArrys[0]);
				var keyam = chagecity();
				var StatusData = "";
				Spider_Job_ID = "Spider_Job_ID_" + random();
				data = {
					Spider_Job_ID: Spider_Job_ID,
					keywordMarket: keyam,
					txtKeywordsMaxNum: txtKeywordsMaxNum,
					productTitle: productTitle,
					txtKeywordsToSearch: txtKeywordsToSearch
				};
				/*data = {'amzMarket':'US','amzCommissionRate':'0.15','txtCost':'11','txtPrice':'11','txtLength':'16.74','txtWidth':'9.65','txtHeight':'6.604','txtWeightAcutal':'0.321','txtFreightCost':'40'}*/

				data = "data=" + JSON.stringify(data);

				keyResultF(data);
				$(".emptyClick").hide();
				/*每个3秒请求接口 */
				StatusData = {Spider_Job_ID: Spider_Job_ID}
				var StatusDatas = "data=" + JSON.stringify(StatusData);
				keyStatus(StatusDatas, false);
				$(this).text("停止");
			} else if ($(this).text() == '停止') {
				$(".progressMsg").text("分析完成，以下是建议的search term");
				$(".progress-bar").css("width", "100%");
				keyStopClick();
			}
		}

	})

	/*点击停止按钮*/
	function keyStopClick() {
		var _data;
		_data = {Spider_Job_ID: Spider_Job_ID};
		_data = "data=" + JSON.stringify(_data);
		//console.log("停止" + _data)
		$.ajax({
			type: "post",
			dataType: "json",
			url: "http://" + keyUrl + "/api/StopSpiderJob_api.php",
			data: _data,
			beforeSend: function() {

			},
			success: function(msg) {
				if (msg.code == 200) {
					$.ajax({
						type: "post",
						dataType: "json",
						data: _data,
						url: "http://" + keyUrl + "/api/GetSpiderStatus_api.php",
						success: function(msg) {
							clearInterval(t);
							getValue(msg);
							
						},
						error: function() {
							alert("请求失败")
						},
						complete: function() {
							$(".emptyClick").show();
						}
					});

				}
			},
			error: function(msg) {
				alert(msg + "keyajax请求失败");
			}
		});
	}

	function keyResultF(data) {
		$.ajax({
			type: "post",
			dataType: "json",
			data: data,
			cache: false,
			url: "http://" + keyUrl + "/api/AddSpiderJob_api.php",
			success: function(msg) {

			},
			error: function(msg) {
				alert(msg + "keyajax请求失败");
			}
		});
	}

	/*产生20位的随机小数，由数字加字符组成*/
	function random() {
		var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "g"];
		var result = "";
		for (var i = 0; i < 20; i++) {
			r = Math.floor(Math.random() * 20);
			result += data[r];
		}
		return result;
	}

	function chagecity() {
		var am = "US";
		if (keywordMarket == '美国亚马逊') {
			am = 'US';
		} else if (keywordMarket == '英国亚马逊') {
			am = 'UK';
		} else if (keywordMarket == '法国亚马逊') {
			am = 'FR';
		} else if (keywordMarket == '德国亚马逊') {
			am = 'DE';
		}

		return am;
	}

	/*清空数据*/
	$(".emptyClick").on("click", function() {
		spanArrys = [];
		spanArry = [];
		$("#productTitle").val("");
		$("#txtKeywordsToSearch").siblings(".keySpanS").remove();
		$(".divDisplay").css("display", "none");
		$(".progress-bar").css("width", "0");
		$(".progressMsg").text("抓取未开始，请输入关键词后，点击'开始抓取'");

	})
})